package com.ruoyi.project.applet.service.impl;

import java.util.*;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.applet.domain.PrizeHistory;
import com.ruoyi.project.applet.domain.Ratio;
import com.ruoyi.project.applet.domain.Wallet;
import com.ruoyi.project.system.domain.SysUserWx;
import com.ruoyi.project.system.service.impl.SysUserWxServiceImpl;
import io.swagger.models.auth.In;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.project.applet.mapper.PrizeMapper;
import com.ruoyi.project.applet.domain.Prize;
import com.ruoyi.project.applet.service.IPrizeService;

/**
 * 奖品Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-06-03
 */
@Service
public class PrizeServiceImpl implements IPrizeService 
{

    private Logger logger = LoggerFactory.getLogger("PrizeServiceImpl");

    @Autowired
    private PrizeMapper prizeMapper;

    @Autowired
    private PrizeHistoryServiceImpl prizeHistoryService;

    @Autowired
    private WalletServiceImpl walletService;

    @Autowired
    private RatioServiceImpl ratioService;

    @Autowired
    private SysUserWxServiceImpl sysUserWxService;

    /**
     * 查询奖品
     * 
     * @param id 奖品ID
     * @return 奖品
     */
    @Override
    public Prize selectPrizeById(Long id)
    {
        return prizeMapper.selectPrizeById(id);
    }

    /**
     * 查询奖品列表
     * 
     * @param prize 奖品
     * @return 奖品
     */
    @Override
    public List<Prize> selectPrizeList(Prize prize)
    {
        return prizeMapper.selectPrizeList(prize);
    }

    /**
     * 新增奖品
     * 
     * @param prize 奖品
     * @return 结果
     */
    @Override
    public int insertPrize(Prize prize)
    {
        prize.setCreateTime(DateUtils.getNowDate());
        return prizeMapper.insertPrize(prize);
    }

    /**
     * 修改奖品
     * 
     * @param prize 奖品
     * @return 结果
     */
    @Override
    public int updatePrize(Prize prize)
    {
        return prizeMapper.updatePrize(prize);
    }

    /**
     * 批量删除奖品
     * 
     * @param ids 需要删除的奖品ID
     * @return 结果
     */
    @Override
    public int deletePrizeByIds(Long[] ids)
    {
        return prizeMapper.deletePrizeByIds(ids);
    }

    /**
     * 删除奖品信息
     * 
     * @param id 奖品ID
     * @return 结果
     */
    @Override
    public int deletePrizeById(Long id)
    {
        return prizeMapper.deletePrizeById(id);
    }

    @Override
    public Map point(String openId) {
        Wallet wallet = walletService.getWalletMoney(openId);
        Map<Object, Object> result = new HashMap<>();
        result.put("number", wallet.getNumber());
        PrizeHistory prizeHistory = new PrizeHistory();
        prizeHistory.setUserId(openId);
        List<PrizeHistory> historyList = prizeHistoryService.selectPrizeHistoryList(prizeHistory);
        result.put("historyList", historyList);
        return result;
    }

    @Override
    public AjaxResult draw(String openId) {
        //校验用户抽奖点数是否足够
        List<Ratio> ratios = ratioService.selectRatioList(new Ratio());
        Integer number = ratios.get(0).getThirdRatio().intValue();
        Wallet wallet = walletService.getWalletMoney(openId);
        if (wallet.getNumber() < number) {
            return AjaxResult.error("抽奖点数不足");
        }

        List<Prize> prizes = prizeMapper.selectPrizeList(new Prize());
        int prizeCount = 0;
        for (Prize prize : prizes) {
            prizeCount += prize.getQuantity();
        }
        if (prizeCount == 0) {
            //生成一条抽奖记录
            PrizeHistory prizeHistory = new PrizeHistory();
            prizeHistory.setName("未中奖");
            prizeHistory.setUserId(openId);
            prizeHistory.setNumber(number);
            prizeHistory.setCreateTime(DateUtils.getNowDate());
            prizeHistoryService.insertPrizeHistory(prizeHistory);
            logger.info("用户:" + openId + "未中奖");
            return AjaxResult.success("未中奖");
        }
        //总权重
        int totalWeight = 0;
        for (Prize prize : prizes) {
            totalWeight += prize.getWeight() * prize.getQuantity();
        }
        Random random = new Random();
        int drawPoint = random.nextInt(totalWeight);

        for (Prize prize : prizes) {
            if (prize.getQuantity() <= 0) continue;

            int effectiveWeight = prize.getWeight().intValue() * prize.getQuantity().intValue();

            if (drawPoint < effectiveWeight) {
                prize.setQuantity(prize.getQuantity() - 1);
                prizeMapper.updatePrize(prize);

                //生成一条抽奖记录
                PrizeHistory prizeHistory = new PrizeHistory();
                prizeHistory.setName(prize.getName());
                prizeHistory.setUserId(openId);
                prizeHistory.setNumber(number);
                prizeHistory.setCreateTime(DateUtils.getNowDate());
                prizeHistoryService.insertPrizeHistory(prizeHistory);
                //钱包扣除抽奖点数
                wallet.setNumber(wallet.getNumber() - number);
                walletService.updateWallet(wallet);
                //如果抽中会员天数，则延期
                SysUserWx sysUserWx = sysUserWxService.selectSysUserWxByOpenId(openId);
                if (sysUserWx.getExpirationTime() == null) {
                    Date currentDate = new Date();
                    // 使用Calendar类来操作日期
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(currentDate);
                    calendar.add(Calendar.DAY_OF_MONTH, prize.getDay()); // 加上30天

                    // 获取新的日期
                    Date newDate = calendar.getTime();
                    sysUserWx.setExpirationTime(newDate);
                } else {
                    Date expirationTime = sysUserWx.getExpirationTime();
                    // 使用Calendar类来操作日期
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(expirationTime);
                    calendar.add(Calendar.DAY_OF_MONTH, prize.getDay()); // 加上30天

                    // 获取新的日期
                    Date newDate = calendar.getTime();
                    sysUserWx.setExpirationTime(newDate);

                }
                sysUserWx.setIsVip(Constants.IS_VIP);
                sysUserWxService.updateSysUserWx(sysUserWx);
                logger.info("会员:{},抽中会员天数", sysUserWx.getOpenId(), prize.getDay());
                return AjaxResult.success(prize.getName());
            }

            drawPoint -= effectiveWeight;
        }

        return AjaxResult.success();
    }
}
